package com.zhuky.controller;

import com.zhuky.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;


/**
 * 登录相关操作
 * @author zhu
 * @date 2018-08-26 09:35:11
 */
@Slf4j
@Controller
public class LoginController {
    /**
     * 登录
     * @param loginName
     * @param password
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String doLogin(String loginName, String password, HttpSession session){
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            SysUser user = (SysUser) subject.getPrincipal();
            log.info("--- 登陆成功 --- 当前登陆的用户是:{}",user);
            session.setAttribute("user", user);
            return "redirect:index";
        }catch (Exception e) {
            log.warn("--- 登录失败 ---");
            return "redirect:login";
        }
    }

    /**
     * 跳转
     * @return
     */
    @GetMapping("/login")
    public String login(){
        return "login.html";
    }

    /**
     *
     * @return
     */
    @RequiresRoles("admin")
    @GetMapping("/index")
    public String index(){
        return "index.html";
    }

    /**
     *
     * @return
     */
    @RequiresRoles("user")
    @GetMapping("/user")
    public String user(){
        return "user.html";
    }
}
